<template>
  <!-- 主查询表单（简洁高级风格） -->
  <el-card class="elegant-query-card">
    <el-form
        :inline="true"
        :model="queryForm"
        class="main-query-form elegant-query-form"
        label-width="80px"
    >
      <el-form-item label="商品名称">
        <el-input
            v-model="queryForm.gname"
            placeholder="请输入商品名称"
            clearable
            class="elegant-input"
        />
      </el-form-item>

      <el-form-item label="审核状态">
        <el-select
            v-model="queryForm.processStatus"
            placeholder="全部"
            clearable
            class="elegant-select"
            style="width: 150px"
        >
          <el-option label="全部" value="" />
          <el-option label="未审核" value="2" />
          <el-option label="审核通过" value="1" />
          <el-option label="审核未通过" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="生效时间">
        <el-date-picker
            v-model="queryForm.beginTime"
            type="date"
            placeholder="开始日期"
            class="elegant-date"
            value-format="YYYY-MM-DD"
            @change="handleBeginTimeChange"
            style="width: 100px"
        />
      </el-form-item>

      <el-form-item label="失效时间">
        <el-date-picker
            v-model="queryForm.endTime"
            type="date"
            placeholder="结束日期"
            class="elegant-date"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledEndDate"
            style="width: 100px"
        />
      </el-form-item>

      <el-form-item class="query-buttons">
        <el-button type="primary" @click="queryWithCondition" class="elegant-btn elegant-primary">查询</el-button>
        <el-button @click="clearQueryForm" class="elegant-btn elegant-default">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 详情 -->
  <ViewDialog ref="viewDialogRef" @refresh-table="query" />

  <!-- 审核跟踪对话框 -->
  <AuditTraceDialog ref="auditTraceDialogRef" />

  <!-- 商品价格调整表格 -->
  <el-card class="elegant-table-card">
    <template #header>
      <div class="table-header">
        <span class="table-title">价格调整列表</span>
        <span class="table-tips">共 {{ pageInfo.total }} 条记录</span>
      </div>
    </template>
    <el-table :data="priceTableData" class="elegant-table">
      <el-table-column prop="id" label="序号" min-width="50" align="center" />
      <el-table-column prop="gname" label="商品名称" min-width="180" show-overflow-tooltip />
      <el-table-column prop="oldShopPrice" label="原商城价" min-width="100" align="center">
        <template #default="scope">
          <span class="price-cell">¥{{ scope.row.oldShopPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="adjustShoppingPrice" label="调整后商城价" min-width="120" align="center">
        <template #default="scope">
          <span class="price-cell highlight">¥{{ scope.row.adjustShoppingPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="希望价格生效时间" min-width="160" align="center">
        <template #default="scope">
          <span class="date-cell">{{ formatDateTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="processStatus" label="审批状态" min-width="100" align="center">
        <template #default="scope">
          <span
              :class="{
                'status-unreviewed': scope.row.processStatus === '2',
                'status-passed': scope.row.processStatus === '1',
                'status-rejected': scope.row.processStatus === '0'
              }"
              class="status-badge"
          >
            {{
              scope.row.processStatus === '0' ? '审核未通过' :
                  scope.row.processStatus === '1' ? '审核通过' : '未审核'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <!-- 根据审核状态动态显示内容 -->
            <template v-if="scope.row.processStatus === '2'">
              <!-- 未审核状态：显示可点击的审核按钮 -->
              <el-button type="primary" size="small" @click="handleView(scope.row)" class="elegant-btn elegant-primary">审核</el-button>
            </template>
            <template v-else>
              <!-- 已审核（通过/未通过）：显示"已审核"文本（样式灰化） -->
              <span class="audited-text">已审核</span>
            </template>
            <el-button type="info" size="small" @click="handleAuditTrace(scope.row)" class="elegant-btn elegant-info">审核跟踪</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pageInfo.pageNum"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[3, 5, 7]"
          :total="pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          class="elegant-pagination"
      />
    </div>
  </el-card>
</template>

<script setup>
import {ref, onMounted, watch} from "vue";
import api from '@/utils/request.js';
import {ElMessage, ElMessageBox} from "element-plus";
import ViewDialog from './viewDialog.vue';
import AuditTraceDialog from "@/views/check/AuditTraceDialog.vue";

const viewDialogRef = ref();

// 点击"查看"时触发
const handleView = (row) => {
  viewDialogRef.value.openViewDialog(row);
};

const auditTraceDialogRef = ref();

// 表单数据
const form = ref({
  goodsId: '',
  goodsName: '',
  goodsStock: '',
  originalMarketPrice: '',
  originalMallPrice: '',
  adjustWay: 'absolute',
  percent: '',
  adjustMarketPrice: '',
  adjustShoppingPrice: '',
  beginTime: '',
  endTime: '',
  reason: '',
  remark: ''
});

// 计算调整后价格
const calculateAdjustedPrices = () => {
  if (!form.value.originalMarketPrice || !form.value.originalMallPrice) {
    form.value.adjustMarketPrice = '';
    form.value.adjustShoppingPrice = '';
    return;
  }

  const originalMarket = Number(form.value.originalMarketPrice) || 0;
  const originalMall = Number(form.value.originalMallPrice) || 0;
  let adjustValue = 0;
  const percentStr = form.value.percent ? String(form.value.percent).trim() : '';

  if (form.value.adjustWay === 'percentage') {
    if (!percentStr) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    const percentNum = Number(percentStr.replace('%', ''));
    adjustValue = percentNum / 100;

    if (isNaN(adjustValue) || adjustValue < 0) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    form.value.adjustMarketPrice = (originalMarket * adjustValue).toFixed(2);
    form.value.adjustShoppingPrice = (originalMall * adjustValue).toFixed(2);
  } else {
    if (!percentStr) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    adjustValue = Number(percentStr);

    if (isNaN(adjustValue) || adjustValue < 0) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    form.value.adjustMarketPrice = adjustValue.toFixed(2);
    form.value.adjustShoppingPrice = adjustValue.toFixed(2);
  }
};

watch(() => form.value.originalMarketPrice, () => {
  calculateAdjustedPrices();
});

/* 主表格查询逻辑 */
const queryForm = ref({
  gname: "",
  processStatus: "",
  beginTime: "",
  endTime: ""
});

const pageInfo = ref({
  pageNum: 1,
  pageSize: 3,
  total: 0
});

const priceTableData = ref([]);

const query = () => {
  const queryParam = { ...queryForm.value, ...pageInfo.value };
  api.get("priceAdjust/list", queryParam).then(result => {
    if (result.code === 200) {
      pageInfo.value.total = result.data.total;
      priceTableData.value = result.data.list;
    }
  });
};

const queryWithCondition = () => {
  pageInfo.value.pageNum = 1;
  query();
};

const clearQueryForm = () => {
  queryForm.value = {
    gname: "",
    processStatus: "",
    beginTime: "",
    endTime: ""
  };
  pageInfo.value.pageNum = 1;
  query();
};

const pageSizeChange = (pageSize) => {
  pageInfo.value.pageSize = pageSize;
  pageInfo.value.pageNum = 1;
  query();
};

const pageNumChange = (pageNum) => {
  pageInfo.value.pageNum = pageNum;
  query();
};

/* 工具方法 */
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

// 禁用结束日期的逻辑：结束日期不能早于开始日期
const disabledEndDate = (time) => {
  if (queryForm.value.beginTime) {
    const beginDate = new Date(queryForm.value.beginTime);
    return time.getTime() < beginDate.getTime();
  }
  return false;
};

// 开始日期变化时，清空结束日期
const handleBeginTimeChange = () => {
  if (queryForm.value.endTime && queryForm.value.beginTime) {
    const beginDate = new Date(queryForm.value.beginTime);
    const endDate = new Date(queryForm.value.endTime);
    if (endDate < beginDate) {
      queryForm.value.endTime = '';
    }
  }
};

// 点击"审核跟踪"时触发
const handleAuditTrace = (row) => {
  auditTraceDialogRef.value.openAuditTraceDialog(row);
};

/* 初始化 */
onMounted(() => {
  query();
});
</script>

<style scoped>
/* 简洁高级风格样式 */
.elegant-query-card {
  background: #ffffff;
  border: none;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.elegant-query-form {
  padding: 20px;
}

.elegant-query-form :deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.elegant-input {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  background: #ffffff;
  transition: all 0.3s ease;
  font-size: 14px;
}

.elegant-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.elegant-select {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.elegant-date {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.elegant-btn {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  font-size: 14px;
  padding: 10px 20px;
}

.elegant-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.elegant-primary {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
}

.elegant-default {
  background: #ffffff;
  color: #666;
  border: 1px solid #d9d9d9;
}

.elegant-default:hover {
  background: #f5f5f5;
  border-color: #1890ff;
  color: #1890ff;
}

.elegant-info {
  background: linear-gradient(135deg, #52c41a, #389e0d);
  color: white;
}

.query-buttons {
  margin-left: auto;
}

.elegant-table-card {
  border-radius: 12px;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  background: #ffffff;
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.table-title {
  color: #333;
  font-weight: 600;
  font-size: 16px;
}

.table-tips {
  color: #666;
  font-size: 12px;
}

.elegant-table {
  border-radius: 8px;
  overflow: hidden;
}

.elegant-table :deep(th) {
  background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%) !important;
  color: #333;
  font-weight: 600;
  border: none;
  font-size: 14px;
}

.elegant-table :deep(td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 0;
  font-size: 14px;
}

.elegant-table :deep(tr:hover td) {
  background: #fafafa !important;
}

.price-cell {
  font-weight: 600;
  color: #333;
}

.price-cell.highlight {
  color: #1890ff;
  font-weight: 700;
}

.date-cell {
  color: #666;
  font-size: 13px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-unreviewed {
  background: #fff7e6;
  color: #fa8c16;
}

.status-passed {
  background: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background: #fff2f0;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.audited-text {
  display: inline-block;
  padding: 6px 12px;
  margin-right: 8px;
  color: #bfbfbf;
  font-size: 12px;
  line-height: 1.5;
  background: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.pagination-container {
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.elegant-pagination {
  justify-content: center;
}

.elegant-pagination :deep(.btn-prev),
.elegant-pagination :deep(.btn-next),
.elegant-pagination :deep(.number) {
  border: 1px solid #d9d9d9;
  background: white;
  color: #333;
  border-radius: 4px;
}

.elegant-pagination :deep(.number.active) {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
  border-color: #1890ff;
}

.elegant-pagination :deep(.el-pagination__total) {
  color: #666;
}

.elegant-pagination :deep(.el-pagination__jump) {
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .elegant-query-form {
    flex-direction: column;
    align-items: stretch;
  }

  .query-buttons {
    margin-left: 0;
    margin-top: 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .elegant-input,
  .elegant-select,
  .elegant-date {
    width: 100% !important;
  }
}
</style>